<template>
  <div class="markdown-editor-warp">
    <div class="edit-article-title-warp">
      <div class="edit-article-title">
        <el-input
          placeholder="这里写标题哦"
          v-model="articleTitle"
          clearable
          prefix-icon="el-icon-edit"
          @input="checkTitle"
        ></el-input>
      </div>
      <div class="edit-article-title-message">
        <span v-if="titleMessageIsShow" :class="{'not-ready':!titleIsReady,ready:titleIsReady}">
          <i :class="{'el-icon-error': !titleIsReady,'el-icon-success':titleIsReady}"></i>
          {{titleMessage}}
        </span>
      </div>
    </div>
    <mavon-editor
      v-model="content"
      ref="md"
      style="min-height: 800px"
      :ishljs="true"
      codeStyle="atelier-lakeside-dark"
      :toolbars="toolbars"
      @imgAdd="markdownImgAdd"
      @imgDel="markdownImgDel"
    ></mavon-editor>
    <div class="tag-list-warp">
      <div class="tag-list-title-warp">
        <p style="font-size:25px;">请选择你文章的TAG</p>
        <div class="more-data-btn-warp">
          <div  v-if="isHaveTagListData" ><el-button class="pink-btn" @click="moreTagDataBtnClick"  :loading="tagDataIsLoading">{{tagDataIsLoading?"加载中":"加载更多TAG"}}</el-button></div>
          <div v-else><el-button class="have-no-data-info" disabled>已经没有了呀</el-button></div>
        </div>
      </div>
      <div class="tag-list-content-warp">
        <el-checkbox-group v-model="selectTags" size="medium">
          <el-checkbox
            v-for="(item,index) in myTagList"
            :key="index"
            :label="item.tagId"
            border
          >{{item.tagName}}</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
    <div class="article-submit-warp">
      <el-button  @click="submit" class="pink-btn" icon="el-icon-upload2">{{isUpdate?"更新文章":"提交保存"}}</el-button>
    </div>
  </div>
</template>

<script>
import { mavonEditor } from "mavon-editor";
import { request } from "../../network/request";
export default {
  name: "markdownEditor",
  props: {
    isUpdate: {
      type: Boolean,
      default: () => false
    },
    tagList: Array,
    orgMarkDownContent: {
      type: String,
      default: () => ""
    },
    orgArticleTags: {
      type: Array,
      default: () => []
    },
    orgArticleTitle: {
      type: String,
      default: () => ""
    },
    orgArticleId:{
      type: String,
      default:() => ""
    }
  },
  components: {
    mavonEditor
  },
  data() {
    return {
      toolbars:{
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: false, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: false, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
        boxShadow: true
      },
      content: "", //用户输入的内容
      articleTitle: "", //文章的标题
      titleIsReady: false, //表示这篇文章标题是否符合规范
      titleMessageIsShow: true,
      titleMessage: "输入的标题不能为空",
      selectTags: [],
      isHaveTagListData:true,
      tagDataIsLoading:false,
      tagListIndex:0,
      myTagList:[]
    };
  },
  methods: {
    markdownImgAdd(fileName,fileObject){
      //图片大于30M会报请求的实体太大了
      if(fileObject.size/1024/1024<10){
        const loading = this.$loading({
                        lock: true,
                        text: '努力上传中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                        });
        let formData=new FormData();
        formData.append("file",fileObject);
        request({
        url:"/image/uploadArticleImage",
        method:"post",
        data:formData,
        headers:{"Content-Type":"multipart/form-data"}
        }).then(res=>{
        console.log(res);
        if(res.data.status==="ok"){
          loading.close();
          this.$notify({
          title: '成功',
          message: '图片上传成功了',
          type: 'success'
        });
        //将返回的url替换到文本原来的位置
        this.$refs.md.$img2Url(fileName,res.data.imageUrl);
        }else{
          loading.close();
          this.$notify({
          title: '警告',
          message: '图片上传出错了，请重试',
          type: 'warning'
        });
        this.$refs.md.$img2Url(fileName,"");
        }
        }).catch(err=>{
          console.log(err);
          loading.close();
          this.$notify.error({
            title: '错误',
            message: '服务器出错，请稍后再试'
          });
          this.$refs.md.$img2Url(fileName,"");
        })
      }else {
        this.$notify({
          title: '警告',
          message: '图片最大不得超过10M',
          type: 'warning'
        });
        this.$refs.md.$img2Url(fileName,"");
      }
    },
    markdownImgDel(){

    },
    moreTagDataBtnClick(){
      this.tagDataIsLoading=true;
      this.tagListIndex++;
      request({
        url:"/tag/tagList/"+this.$store.getters.getCurrentUser.userId+"/"+this.tagListIndex
      }).then(res=>{
        console.log(res);
        if(res.data.tagList.length>0){
          //拿过来的数据去重
            let obj={};
            this.myTagList=this.myTagList.concat(res.data.tagList).reduce((item,next)=>{
              obj[next.tagId]?"":obj[next.tagId]=true&&item.push(next);
              return item;
            },[]);
            this.tagDataIsLoading=false;
            this.isHaveTagListData=true;
        }else{
          this.tagDataIsLoading=false;
          this.isHaveTagListData=false;
        }
      }).catch(err=>{
        console.log(err);
        this.$message.error('获取数据失败，请稍后再试');
        this.tagDataIsLoading=false;
        this.isHaveTagListData=true;
        this.tagListIndex--;
      })
    },
    //验证输入是否符合规范
    checkTitle() {
      if (this.articleTitle.trim() == "") {
        this.titleMessage = "输入的标题不能为空";
        this.titleMessageIsShow = true;
        this.titleIsReady = false;
      } else if (this.articleTitle.length >= 100) {
        this.titleMessage = "输入的内容不能超过五十个汉字或者一百个英文字符";
        this.titleMessageIsShow = true;
        this.titleIsReady = false;
      } else {
        this.titleMessage = "符合规范";
        this.titleMessageIsShow = true;
        this.titleIsReady = true;
      }
    },
    // 提交
    submit() {
      if (!this.isUpdate) {
        //这里进行文章的创建操作
        if (this.titleIsReady && this.content.trim() != "") {
          this.$confirm("是否确定提交文章?", "主人请确认", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
              // console.log("标题：" + this.articleTitle);
              // console.log(this.content);
              // // console.log(this.html);
              // console.log(this.selectTags);
              // this.articleBody = this.html;
              const loading = this.$loading({
                        lock: true,
                        text: '提交中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                        });
              request({
                url: "/article/saveArticle",
                method: "post",
                data: {
                  userId: this.$store.getters.getCurrentUser.userId, //使用Vuex里的保存的用户ID
                  articleTitle: this.articleTitle,
                  articleMarkDown: this.content,
                  articleTagList:this.selectTags
                }
              }).then(res => {
                // console.log(res);
                  if(res.data.status==="ok"){
                    //等待数据存储完成后提示
                  this.$message({
                    type: "success",
                    message: "提交成功!"
                  });
                  }else {
                  this.$message({
                    type: "warning",
                    message: "提交失败!"
                  });
                  }
                  loading.close();
                }).catch(err => {
                  loading.close();
                  console.log(err);
                });
            }).catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        }
      } else {
        //这里进行文章的更新操作
        if (this.titleIsReady && this.content.trim() != ""){
          console.log("文章更新了"+this.orgArticleId);
          const loading = this.$loading({
                        lock: true,
                        text: '修改中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                        });
          request({
            url:"/article/updateMyArticle",
            method:"post",
            data:{
              articleId:this.orgArticleId,
              articleTitle: this.articleTitle,
              articleMarkDown: this.content,
              articleTagList:this.selectTags
            }
          }).then(res=>{
            console.log(res);
            if(res.data.status==="ok"){
              this.$message({
                    type: "success",
                    message: "更新成功!"
                  });
            }else{
              this.$message({
                    type: "warning",
                    message: "更新未完成!"
                  });
            }
            loading.close();
          }).catch(err=>{
            loading.close();
            console.log(err);
            this.$message.error('服务器出错，请稍后再试');
          })
        }
      }
    }
  },
  created() {
    if (this.isUpdate) {
      this.content = this.orgMarkDownContent;
      this.selectTags = this.orgArticleTags;
      this.articleTitle = this.orgArticleTitle;
      this.titleMessage = "符合规范";
      this.titleIsReady = true;
    }
    this.myTagList=this.tagList;
  }
};
</script>

<style>
.markdown-editor-warp {
  padding: 20px;
}
.ready {
  color: green;
}
.not-ready {
  color: red;
}
.edit-article-title-warp {
  display: flex;
  align-items: center;
  justify-content: left;
  padding: 20px 0;
}
.edit-article-title {
  flex: 3;
}
.edit-article-title-message {
  flex: 2;
}
/* tag容器 */
.tag-list-warp {
  margin: 10px 0;
}
.tag-list-title-warp,
.tag-list-content-warp,
.article-submit-warp {
  padding: 20px 20px;
}
.tag-list-title-warp {
  color: skyblue;
  display: flex;
  justify-content: left;
  align-items: center;
}
.more-data-btn-warp {
  width: 150px;
  padding: 0 10px;
}
.el-checkbox {
  margin: 5px 15px;
}
</style>